{% extends "base.html" %}
{% load i18n %}
{% load static %}
{% block content %}
    <div id="content">

    <!-- Begin Page Content -->
    <div class="container-fluid">

        <!-- Page Heading -->
        <h1 class="h3 mb-2 text-gray-800">上传分发文件</h1>

        <!-- 确认模态框 -->
        <div class="modal fade" id="confirmModal" tabindex="-1" role="dialog" aria-labelledby="confirmModalLabel" aria-hidden="true">
          <div class="modal-dialog" role="document">
            <div class="modal-content">
              <!-- 模态框头部 -->
              <div class="modal-header">
                <h5 class="modal-title" id="confirmModalLabel">确认操作</h5>
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                  <span aria-hidden="true">&times;</span>
                </button>
              </div>
              <!-- 模态框主体内容 -->
              <div class="modal-body">
                您确定要对文件 <span id="tf_msg" class="text-danger">  </span> 进行删除操作吗？该操作无法撤销
              </div>
              <div class="modal-body">
                <label class="mr-3 w-100"><span id="confirm_msg" class="text-danger"></span></label>
              </div>
              <!-- 模态框底部 -->
              <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                <button type="button" class="btn btn-danger" id="confirmButton" onclick="deleteFile()">确认</button>
              </div>
            </div>
          </div>
        </div>

        <!-- DataTales Example -->
        <div class="card shadow mb-4">
            <div class="card-header py-3">
                <button type="button" class="btn btn-sm btn-primary mr-2" id="uploadButton" onclick="uploadFile()" disabled>上传文件</button>
                <span id="msg" class="text-danger"></span>
            </div>

            <div class="card-body">

                <!-- 文件上传框 -->

                <div id="fileUploadDiv">
                    <div class="form-group d-flex align-items-center">
                        <label for="fileUpload"><span class="text-danger">*</span> 选择文件：</label>
                        <!-- 文件选择区域 -->
                        <div class="col-md-5">
                            <div class="custom-file">
                                <input type="file" class="custom-file-input" id="fileUpload" onchange="showFileName()">
                                <label class="custom-file-label" for="fileUpload">点击进行文件上传</label>
                            </div>
                        </div>
                        <label for="fileUpload"><span class="text-danger">*</span> 为避免文件名重复，会对上传后的文件名称添加前缀随机字符</label>
                    </div>
                    <!-- 显示文件名 -->
                    <div id="fileNameDisplay" class="mt-2" style="display: none;">
                        <p>已选择文件：<span id="fileName"></span></p>
                    </div>
                    <!-- 上传状态 -->
                    <div id="uploadStatus" style="margin-top: 10px; display: none;">
                        <p id="statusMessage"></p>
                    </div>
                </div>
                <br>
                <div class="form-group d-flex align-items-center">
                    <label for="dest_dir" class="mr-4"><span class="text-danger">*</span>&nbsp;分发目录:</label>
                    <input type="text" class="form-control" style="width: 40.5%;" id="dest_dir" placeholder='请按照标准格式输入, 例如 {"Linux":"/tmp","Windows":"C:\\\\Windows\\\\"}'>
                </div>
                <br>
                <div class="form-group">
                    <label for="inputType1"><span class="text-danger">*</span>&nbsp;分发方式:&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="exampleRadios1" id="salt_transfer" value="option1" checked>
                        <label class="form-check-label" for="salt_transfer">SaltStack</label>
                    </div>
                    <div class="form-check form-check-inline">
                        <input class="form-check-input" type="radio" name="exampleRadios1" id="an_transfer" value="option2">
                        <label class="form-check-label" for="an_transfer">Ansible</label>
                    </div>
                </div>
                <br>

                <label for="inputType2"> <span class="text-danger">*</span> 已上传文件, 仅保留最近7天 :&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</label>
                <br>
                <!-- 主机组列表 -->
                <div class="table-responsive">
                    <table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>文件名称</th>
                                <th>分发目录</th>
                                <th>分发方式</th>
                                <th>用户</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tfoot>
                            <tr>
                                <th>ID</th>
                                <th>文件名称</th>
                                <th>分发目录</th>
                                <th>分发方式</th>
                                <th>用户</th>
                                <th>创建时间</th>
                                <th>操作</th>
                            </tr>
                        </tfoot>
                        <tbody>
                            <tr style="display: none;">
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                                <td></td>
                            </tr>
                            {% for each_transfer_file in all_transfer_files %}
                            <tr>
                                <td>{{ each_transfer_file.id }}</td>
                                <td>{{ each_transfer_file.name }}</td>
                                <td>{{ each_transfer_file.dest_dir }}</td>
                                <td>{{ each_transfer_file.get_type_display }}</td>
                                <td>{{ each_transfer_file.user }}</td>
                                <td>{{ each_transfer_file.create_time }}</td>
                                <td>
                                    <button type="button" class="btn btn-info btn-sm" onclick="get_rowid(this)" id="{{ each_transfer_file.id }}" value="{{ each_transfer_file.name }}">删除</button>
                                </td>
                            </tr>
                            {% endfor %}
                        </tbody>
                    </table>
                </div>

            </div>
        </div>

    </div>
    <!-- /.container-fluid -->
    <div id="load" class="position-fixed w-100 h-100"
     style="top: 0; left: 0; background: rgba(255, 255, 255, 0.2); z-index: 1100; display: none;
            justify-content: center;
            align-items: center;">
        <div class="spinner-border text-success" role="status" style="width: 3rem; height: 3rem; position: absolute; top: 50%; left: 50%; margin-top: -1.5rem; margin-left: -1.5rem;">
        <span class="sr-only">加载中...</span>
    </div>
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
{% endblock content %}
{% block js %}
    <script type="text/javascript">
        // 设置加载图片
        function loading() {
            document.getElementById('load').style.display = 'flex';
        };

        // 移除加载图片
        function loading_remove() {
            document.getElementById('load').style.display = 'none';
        };

        // 移除reminder
        function reminder_remove() {
            var reminder_msg = document.getElementById("msg");
            reminder_msg.innerHTML = '';
        };

        function showFileName() {
            const fileInput = document.getElementById("fileUpload");
            const fileName = document.getElementById("fileName");
            const fileNameDisplay = document.getElementById("fileNameDisplay");
            const uploadButton = document.getElementById("uploadButton");

            if (fileInput.files.length > 0) {
                fileName.textContent = fileInput.files[0].name;
                fileNameDisplay.style.display = "block";
                uploadButton.disabled = false;
            } else {
                fileNameDisplay.style.display = "none";
                uploadButton.disabled = true;
            }
        }

        function get_rowid(button) {
            // 设置确认按钮的 data-id 属性
            document.querySelector('#confirmButton').setAttribute('data-id', button.id);
            document.getElementById("tf_msg").innerHTML = button.value;

            // 显示确认框
            $('#confirmModal').modal('show');
        }

        function uploadFile() {
            var reminder_msg = document.getElementById("msg");
            const uploadStatus = document.getElementById("uploadStatus");
            const statusMessage = document.getElementById("statusMessage");

            const salt_transfer = document.getElementById('salt_transfer');
            const an_transfer = document.getElementById('an_transfer');
            var transfer_type = "0";
            if (salt_transfer.checked) {
                transfer_type = "0";
            } else {
                transfer_type = "1";
            }

            let fileInput = $('#fileUpload')[0].files[0];  // 获取文件
            let dest_dir_content = $('#dest_dir').val().trim();  // 获取文本并去除空格
            // 检查文本输入是否为空
            if (!dest_dir_content) {
                reminder_msg.innerHTML = 'Reminder: 分发目录输入不可为空';
                return;
            }
            let formData = new FormData();
            formData.append('file', fileInput);
            formData.append('dest_dir', dest_dir_content);
            formData.append('transfer_type', transfer_type);

            $.ajax({
                url: '/upload_transfer_file/',
                type: 'POST',
                data: formData,
                processData: false,
                contentType: false,
                beforeSend: function () {
                    statusMessage.textContent = "文件读取中，请稍候...";
                    uploadStatus.style.display = "block";
                    loading();
                },
                success: function (data) {
                    loading_remove()
                    if (data.status === 0) {
                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                        location.reload();
                    } else {
                        reminder_msg.innerHTML = 'Reminder: ' + data.msg;
                    }
                    uploadStatus.style.display = "none";
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                    loading_remove()
                    reminder_msg.innerHTML = 'Reminder: ' + errorThrown;
                    uploadStatus.style.display = "none";
                }
            });
        }

        function deleteFile() {

            $.ajax({
                type: "post",
                url: "/delete_transfer_file/",
                dataType: "json",
                data: {
                    tf_id: document.querySelector('#confirmButton').getAttribute('data-id'),
                },
                complete: function () {
                },
                success: function (data) {
                    if (data.status === 0) {
                        location.reload();
                    }
                },
                error: function (XMLHttpRequest, textStatus, errorThrown) {
                }
            });
        }
    </script>
{% endblock %}